package com.xneure.code;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.xneure.utils.ObjectUtil;
import com.xneure.utils.PackageUtil;
import com.xneure.utils.intf.SystemListener;

public class XneureContextInitialize implements ServletContextListener,HttpSessionListener{
	private List<SystemListener> listenerList;

	@Override
	public void contextInitialized(ServletContextEvent sce){
		this.listenerList = new ArrayList<SystemListener>(20);
		String cfg = sce.getServletContext().getInitParameter("init-scan");
		if(ObjectUtil.isNull(cfg)){
			cfg = "";
		}
		// assist();//调试程序
		InheritedBeanConvert.proxyListener();
		List<Class<SystemListener>> resourceUrls = PackageUtil.getClassList("com.xneure,".concat(cfg),SystemListener.class);
		for(Class<SystemListener> s:resourceUrls){
			SystemListener newInstance = ObjectUtil.newInstance(s);
			newInstance.start(sce);
			listenerList.add(newInstance);
		}
	}

	// private void assist(){ 
	// XneureCL xcl = new XneureCL();
	// ClassLoader cl = this.getClass().getClassLoader();
	// String input = StrUtil.streamToStr(cl.getResourceAsStream("apache.key"));
	// xcl.setReserve(true);
	// xcl.loadClass(SimpleEncode.decodeBase64(input));
	// }
	@Override
	public void contextDestroyed(ServletContextEvent sce){
		for(SystemListener sl:listenerList){
			sl.stop(sce);
		}
	}

	@Override
	public void sessionCreated(HttpSessionEvent se){
		for(SystemListener sl:listenerList){
			sl.sessionCreated(se);
		}
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se){
		for(SystemListener sl:listenerList){
			sl.sessionDestroyed(se);
		}
	}
}
